import axios, { InternalAxiosRequestConfig, AxiosResponse, AxiosError } from 'axios'
import { message } from 'antd'
import { useUserStore } from '@/store/user'

const instance = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 8000,
  // 允许跨域
  withCredentials: true
})

instance.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const token = useUserStore.getState().token
    if (token) {
      config.headers.Authorization = 'Bearer ' + token
    }
    // icode 30天过期
    config.headers.icode = 'FD1C6FDDB72FEA56'
    return {
      ...config
    }
  },
  (error: AxiosError) => {
    return Promise.reject(error)
  }
)

instance.interceptors.response.use(
  (response: AxiosResponse) => {
    const data = response.data

    if (data.code === 500001) {
      // 未登录&登录token失效
      useUserStore.getState().logout()
      location.href = '/login'
      message.error(data.msg)
    } else if (data.code != 0) {
      // 接口返回错误
      message.error(data.msg)
      return Promise.reject(data)
    } else {
      return data
    }
  },
  (error: AxiosError) => {
    message.error(error.message)
    return Promise.reject(error)
  }
)
export default instance
